import axios, { type AxiosResponse, AxiosError } from "axios";
import { ElMessage } from "element-plus";
import type { APIRES } from "@/hooks/types";
import router from "@/router";
import { useToken } from "./storage";

axios.defaults.headers["Content-Type"] = "application/json;chart-set=utf-8;";

const service = axios.create({
  baseURL: "",
  // timeout: 60000, // 超时时间
});

service.interceptors.request.use((config) => {
  // console.log("config", config);
  if (!config.headers.noToken) {
    config.headers.Authorization = useToken();
  }
  return config;
});

service.interceptors.response.use(
  (res: APIRES) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const message = res.data.message || "系统未知错误，请联系管理员！";
    // 二进制数据则直接返回
    if (["blob", "arraybuffer"].includes(res.request.responseType)) {
      return res;
    }
    if (code == 401) {
      ElMessage.error(message);
      router.push({ path: "/login" });
    } else if (code != 200) {
      ElMessage.error(message);
      return Promise.reject(new Error(message));
    }
    return res;
  },
  (err: AxiosError) => {
    ElMessage.error(err);
    return Promise.reject(err);
  }
);

export default service;
